from django.shortcuts import render
from django.http import HttpResponse
from .models import *
from apitower.models import *
from .verify import *
from django.db.utils import *
import json


@verify_control
def add_asset_api(request):
    """
          @author: 刘宇组
          @ date: 10/24/2018
          本接口为添加资产，需要提交资产名（不可重复）、价格 （必须录入）
          需要提交的数据格式{"asset":"xxx", "price":"xx"}
          @ 整理：董海明
    """
    info = dict(request.POST)
    jprice = info["price"][0]
    try:
        asset = Asset.objects.get(asset_name=info["asset"][0]).replace(" ", "")
    except Asset.DoesNotExist:
        Asset.objects.create(asset_name=asset, price=jprice)
        return HttpResponse(json.dumps({"message": "资产添加成功"}))
    except IntegrityError:
        return HttpResponse(json.dumps({"message": "资产已经存在，不可重复添加"}))


"""
    往房间中增加资产
        需要的内容：{"tower_name":"xxx", "floor_name":"xxx", 
                    "room_name":"xxx", "asset":"xxx", "as_num":"xxx"}
"""


@verify_control
def del_asset_api(request):
    """
        @author: 刘宇组
        @date:10/24/2018
        本接口为删除资产，
            说明：只删除资产名表中的无效资产，不删除存放房间内的有效资产（本资产为过时5年以上，且在存放房间内没有的）
        需要提交的数据格式:{"asset":"xxx"}
        @ 整理：董海明
    """
    info = dict(request.POST)
    try:
        asset = Asset.objects.get(asset_name=info["asset"][0]).replace(" ", "")
    except Asset.DoesNotExist:
        return HttpResponse(json.dumps({"message": "资产名不存在，无需删除"}))
    else:
        room_list = []
        asset_room = asset.interchange_set.all().values()
        for i in asset_room:
            room_list.append(i["room_id"])
        if len(room_list) == 0:
            asset.delete()
            return HttpResponse(json.dumps({"message": "资产删除成功"}))
        elif len(room_list) != 0:
            room_name = []
            for x in room_list:
                r = Room.objects.get(pk=x)
                room_list.append(r.room_num)
            return HttpResponse(json.dumps({"message": "您要删除的资产在以下房间中存在：{}".format(room_name)}))


@verify_control
def find_asset_api(request):
    """
        @author: 刘宇组
        @date: 10/24/2018
        本接口为查询资产，根据所提供 的房间，来查询所在房间内的所有资产
        需要提交的数据：{"tower_name":"xxx", "floor_name":"xxx", "room_name":"xxx"}
        @ 整理：董海明
    """
    info = dict(request.POST)
    try:
        Tower.objects.get(tower_name=info["tower_name"][0]).replace(" ", "")
    except Tower.DoesNotExist:
        return HttpResponse(json.dumps({"message": "输入的楼名不存在，请重新输入"}))
    else:
        try:
            Floor.objects.get(floor_num=info["floor_num"][0]).replace(" ", "")
        except Floor.DoesNotExist:
            return HttpResponse(json.dumps({"message": "输入的楼层不存在，请重新输入"}))
        else:
            try:
                room = Room.objects.get(room_num=info["room_name"][0])
            except Room.DoesNotExist:
                return HttpResponse(json.dumps({"message": "输入的房间号不存在，请重新输入"}))
            else:
                asset_id = []
                asset_list = room.interchange_set.all().values()
                for i in asset_list:
                    x = Asset.objects.get(pk=i["asset_id"]).asset_name
                    asset_id.append(x)
                if len(asset_id) != 0:
                    return HttpResponse(json.dumps({"message": "该房间内有以下商品：{}".format(asset_id)}))


"""
    按资产名，查找在哪些房间中有
        需要提交的内容{"asset":"xxx"}
"""


@verify_control
def change_asset_api(request):
    """
        @author: 刘宇组
        @date: 10/24/2018
        本接口为修改资产名称
        需要的内容{"asset":"xxx", "new_asset":"xxx"}
        @整理：董海明
    """
    info = dict(request.POST)
    try:
        asset = Asset.objects.get(asset_name=info["asset"][0]).replace(" ", "")
    except Asset.DoesNotExist:
        return HttpResponse(json.dumps({"message": "输入的资产不存在，请重新输入"}))
    else:
        asset.objects.update(asset_name=info["new_asset"][0])
        return HttpResponse(json.dumps({"message": "修改成功"}))


def change_price_api(request):
    """
        @author: 董海明
        @date: 10/24.2018
        本接口为修改进价
        需要的内容{"asset":"xxx", "new_price":"xxx"}
    """
    info = dict(request.POST)
    try:
        asset = Asset.objects.get(asset_name=info["asset"][0]).replace(" ", "")
    except Asset.DoesNotExist:
        return HttpResponse(json.dumps({"message": "输入的资产不存在，请重新输入"}))
    else:
        if info["new_price"][0] != "":
            asset.objects.update(price=info["new_price"][0])
            return HttpResponse(json.dumps({"message": "修改成功"}))
        elif info["new_price"][0] == "":
            return HttpResponse(json.dumps({"message": "录入的信息不可以为空"}))


@verify_control
def asset_buy(request):
    """
    资产购买
    @author:郭峰
    @time:2018/10/18
    提交方式:post
    提交数据库格式: 采购格式:{'asset_name':'xxx','pur_num':'数字','user':'xx','save_room':'仓库'}
                仓库格式:{'asset_name':'xxx','room':'xxx','asset_num':'数字'}
    @ 整理： 董海明
    """
    info = dict(request.POST)
    try:
        to = Tower.objects.get(tower_name=info['save_tower'][0])
    except Tower.DoesNotExist:
        return HttpResponse('此楼不存在')
    else:
        try:
            fo = to.floor_set.get(floor_num=info['save_floor'][0])
        except Floor.DoesNotExist:
            return HttpResponse('楼层不存在')
        else:
            try:
                ro = fo.room_set.get(room_num=info['save_room'][0])
            except Room.DoesNotExist:
                return HttpResponse('房间不存在')
            else:
                try:
                    us = User.objects.get(user_name=info['user_name'][0])
                except User.DoesNotExist:
                    return HttpResponse('查无此人')
                else:
                    try:
                        asset_name = Asset.objects.get(asset_name=info['asset_name'][0])

                    except Asset.DoesNotExist:
                        return HttpResponse('资产不再预购范围')

                    else:
                        try:
                            Interchange.objects.get(asset=asset_name)
                        except Interchange.DoesNotExist:
                            Interchange.objects.create(room=ro,
                                                       asset=asset_name,
                                                       asset_num=info['asset_num'][0])
                            return HttpResponse('资产已入库')
                        else:

                            Purchase.objects.create(save_room=ro,
                                                    user=us,
                                                    asset_name=asset_name,
                                                    pur_num=info['asset_num'][0])
                            io = Interchange.objects.get(asset=asset_name)
                            print(io)
                            io.asset_num = io.asset_num + int(info['asset_num'][0])
                            io.save()
                            print(io.asset_num)
                            return HttpResponse(json.dumps({'message': '资产购买成功'}))


@verify_control
def damage_asset_add(request):
    """
        @author:刘宇
        @date:2018/10/19
        本接口为损坏资产移出
        提交方式：POST
        提交格式：{'room_num':'xx','floor_num':'xx',
                    'tower_num':'xx','asset_name':'xxx','asset_num':'xx'}
    """
    info = request.POST
    print(info)
    try:
        tower = Tower.objects.get(tower_name=info['tower_num'])
    except Tower.DoesNotExist:
        return HttpResponse(json.dumps({'message': '没有这个楼'}))
    else:
        try:
            floor = tower.floor_set.get(floor_num=info['floor_num'])
        except Floor.DoesNotExist:
            return HttpResponse(json.dumps({'message': '没有这个层'}))
        else:
            try:
                room = floor.room_set.get(room_num=info['room_num'])
                print(room)
            except Room.DoesNotExist:
                return HttpResponse(json.dumps({'message': '没有这个房间'}))
            else:
                try:
                    asset = Asset.objects.get(asset_name=info['asset_name'])
                except Asset.DoesNotExist:
                    return HttpResponse(json.dumps({'message': '没有这个物品'}))
                else:
                    rom = Interchange.objects.filter(asset=asset).filter(room=room)
                    rom = rom[0]
                    rom.asset_num -= int(info['asset_num'])

                    rom.damage_set.create(damage_num=info['asset_num'])
                    info_dict = {info['asset_name']: {'楼号': info['tower_num'], '层号': info['floor_num'],
                                                      '房间号': info['room_num'], '损坏数量': info['asset_num']}}
                    DamageForm.objects.create(damageform=info_dict)
                    rom.save()
                    return HttpResponse(json.dumps({'message': '添加成功'}))


@verify_control
def damage_asset_find(request):
    """
        @author:刘宇
        @date:2018/10/19
        本接口为报损资产查询
        提交方式：POST
        提交格式：{'room_num':'xx','asset_name':'xxx'}
    """
    info = request.POST
    print(info)
    find_name = info['asset_name']
    room = info['room_num']
    damage = DamageForm.objects.filter(bs_date__year=2018).filter(bs_date__month=10)
    info_dict = {}
    for i in damage:
        for key, value in eval(i.damageform).items():
            if key == find_name and value['房间号'] == room:
                info_dict[key] = value
    context = {'aa': info_dict}
    return render(request, 'asset/damage_find.html', context)


@verify_control
def damage_asset_del(request):
    """
        @author:刘宇
        @date:2018/10/19
        本接口为报损资产删除
        提交方式：POST
        提交格式：{'tower_num':'xx','room_num':'xx','asset_name':'xxx'}

    """

    info = request.POST
    find_name = info['asset_name']
    room = info['room_num']
    tower = info['tower_num']
    damage = DamageForm.objects.filter(bs_date__year=2018).filter(bs_date__month=10)
    info_dict = {}
    for i in damage:
        for key, value in eval(i.damageform).items():
            if key == find_name and value['房间号'] == room and value['楼号'] == tower:
                info_dict[key] = value
    print(info_dict)
    if not info_dict:
        return HttpResponse(json.dumps({'message': '没有该记录'}))
    DamageForm.objects.get(damageform=info_dict).delete()
    return HttpResponse(json.dumps({'message': '删除成功'}))


@verify_control
def asset_inquire(request):
    """
        房间所有物资查询接口
        @auther: 辛光华
        @date: 2018/10/18
        本接口为资产详情查询接口,提交数据格式为{'tower_name': '教学楼',
                                            'floor_num': '3',
                                            'room_num': '311',
                                            'verify_pswd': '123'}

    """
    info = dict(request.POST)
    try:
        tower = Tower.objects.get(tower_name=info['tower_name'][0])
    except Tower.DoesNotExist:
        return HttpResponse('没有这个楼')
    else:
        try:
            floor = tower.floor_set.get(floor_num=info['floor_num'][0])
        except Floor.DoesNotExist:
            return HttpResponse('这楼没这层')
        else:
            try:
                room = floor.room_set.get(room_num=info['room_num'][0])
            except Room.DoesNotExist:
                return HttpResponse('这层没这屋')
            else:
                asset_obj = room.interchange_set.all()
                asset_list = []
                asset_dict = {room.room_num: asset_list}
                x = {}
                for i in asset_obj:
                    x[i.asset.asset_name] = i.asset_num
                asset_list.append(x)
                return HttpResponse(json.dumps(asset_dict))









